package com.smartinput.websocket

import com.smartinput.security.JwtService
import com.smartinput.device.application.service.DeviceService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.socket.server.HandshakeInterceptor
import org.springframework.web.socket.WebSocketHandler
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import java.util.*

@Component
class WebSocketAuthInterceptor : HandshakeInterceptor {
    
    private val logger = LoggerFactory.getLogger(WebSocketAuthInterceptor::class.java)
    
    @Autowired
    private lateinit var jwtService: JwtService
    
    @Autowired
    private lateinit var deviceService: DeviceService
    
    override fun beforeHandshake(
        request: ServerHttpRequest,
        response: ServerHttpResponse,
        wsHandler: WebSocketHandler,
        attributes: MutableMap<String, Any>
    ): Boolean {
        logger.info("=== WebSocketAuthInterceptor开始处理握手 ===")
        logger.debug("请求URI: {}", request.uri)
        
        val queryParams = request.uri.query?.split("&")?.associate { param ->
            val (key, value) = param.split("=")
            key to value
        } ?: emptyMap()

        logger.debug("查询参数: {}", queryParams)
        
        val token = queryParams["token"]
        val deviceId = queryParams["deviceId"]
        
        logger.debug("提取的token: ${token?.take(20)}...")
        logger.debug("提取的deviceId: $deviceId")
        
        if (token == null || deviceId == null) {
            logger.warn("❌ token或deviceId为空")
            return false
        }
        
        // 验证JWT token
        logger.debug("开始验证JWT token...")
        if (!jwtService.validateToken(token)) {
            logger.warn("❌ JWT token验证失败")
            return false
        }
        logger.info("✅ JWT token验证成功")
        
        val userId = jwtService.getUserIdFromToken(token)
        logger.debug("从token中提取的userId: $userId")
        if (userId == null) {
            logger.warn("❌ 无法从token中提取userId")
            return false
        }
        
        // 将用户ID和设备ID存储到session属性中
        attributes["userId"] = userId
        attributes["deviceId"] = deviceId
        
        logger.info("✅ WebSocket握手验证成功，userId=$userId, deviceId=$deviceId")
        
        // 注意：不在这里验证设备归属，允许设备在首次连接时通过认证
        // 设备归属验证将在WebSocket连接建立后的ensureDeviceExists中进行
        
        return true
    }
    
    override fun afterHandshake(
        request: ServerHttpRequest,
        response: ServerHttpResponse,
        wsHandler: WebSocketHandler,
        exception: Exception?
    ) {
        // 握手后的处理，这里不需要特殊处理
    }
} 